﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;

using Recon.Portal.Business;
using Recon.Portal.DataObjects;

namespace Recon.Portal.WebUI
{
    public partial class FileUpload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (((UserVO)Session["CurrentUserVO"]) == null)
            //{
            //    Response.Redirect("ReconSignIn.aspx");
            //}
            if (!Page.IsPostBack)
            {
                FillBank();
            }
        }
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                //1.Insert file detail   2.Get File Detail   3.

                //List<string> fileLines = File.ReadAllLines("F:\file.txt").ToList();
                HttpPostedFile fileBrowse = fuInvoiceState.PostedFile;
                string strFileExt = Path.GetExtension(fuInvoiceState.FileName);
                string strFilename = Path.GetFileName(fuInvoiceState.FileName);
                int filtLength = fuInvoiceState.FileBytes.Length;
                if (strFilename != "" && filtLength > 0)
                {

                    //Code for Insert file detail into pro_file_upload_details table              
                    //fileId =  1111111001;//System.DateTime.Now.ToString("ddMMyyyyhhmmss") + "001";
                    string fileType = ddlFileType.SelectedValue;
                    string bankId = string.Empty;
                    if (fileType == "S")
                    {
                        bankId = ddlBankName.SelectedValue;
                    }

                    fuInvoiceState.PostedFile.SaveAs(Server.MapPath(".") + @"\" + strFilename + ".txt");
                    string OpenPath = Server.MapPath(".") + @"\" + strFilename + ".txt";
                    string FILENAME = OpenPath;

                    //Tempory assignment of value to object


                    UploadHelper objUploadHelper = new UploadHelper();
                    User currentUser = (User)Session["CurrentUserVO"]; //UploadHelper.getTestUser(); 
                    int retval = objUploadHelper.ParseUploadedFile(currentUser, fileType, strFilename, strFileExt, FILENAME, bankId);
                    
                    if (retval == 2)
                    {
                        //ClientScript.RegisterClientScriptBlock(this.GetType(), "SuccessMessage", "<script>alert('File already uploadeded!')</script>");
                        lblMessage.Text = "File already uploadeded!";
                        btnClickPopup.Show();

                    }
                    else if (retval != 0)
                    {
                        //ClientScript.RegisterClientScriptBlock(this.GetType(), "SuccessMessage", "<script>alert('File uploaded successfully!')</script>");
                        lblMessage.Text = "File uploaded successfully!";
                        btnClickPopup.Show();
                        
                    }
                    else
                    {
                        //ClientScript.RegisterClientScriptBlock(this.GetType(), "ErrorMessage", "<script>alert('Error in File upload!')</script>");
                        lblMessage.Text = "Error in File upload!";
                        btnClickPopup.Show();
                    }
                }//End of  using (StreamReader reader = File.OpenText(FILENAME))

                else
                {
                    //ClientScript.RegisterClientScriptBlock(this.GetType(), "SuccessMessage", "<script>alert('Check the file size!')</script>");
                    lblMessage.Text = "Check the file size!";
                    btnClickPopup.Show();
                }

            }

            catch
            {
                lblMessage.Text = "Error in File upload!";
                btnClickPopup.Show();
                throw;
            }
        }

        protected void btnok_Click(object sender, EventArgs e)
        {
            btnClickPopup.Hide();
        }

        protected void ddlFileType_SelectedIndexChanged(object sender, EventArgs e)
        {
            string bankId = string.Empty;
            if(ddlFileType.SelectedValue == "S")
            {
                ddlBankName.Enabled = true;
            }
            else if (ddlFileType.SelectedValue == "I")
            {
                ddlBankName.SelectedIndex = 0;
                ddlBankName.Enabled = false;
                rbFileType.Items.Clear();
                fillFileFormat(ddlFileType.SelectedValue,"0");
            }
            else
            {
                rbFileType.Items.Clear();
                ddlBankName.SelectedIndex = 0;
                ddlBankName.Enabled = false;
            }
        }

        private void FillBank()
        {
            BankDAO bankDAO = DAOFactory.getBankDAO();
            List<Bank> bankLst = bankDAO.getAllBanksByCustomer(((User)Session["CurrentUserVO"]).CustomerID);
            if (bankLst != null && bankLst.Count > 0)
            {
                for (int i = 0; i < bankLst.Count; i++)
                {
                    ddlBankName.Items.Add(bankLst[i].BankID.Trim() + " - " + bankLst[i].BankName.Trim());
                    ddlBankName.Items[i + 1].Value = (bankLst[i].BankID.Trim());
                }
            }
        }

        protected void ddlBankName_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlBankName.SelectedValue != "0")
            {
                rbFileType.Items.Clear();
                fillFileFormat(ddlFileType.SelectedValue, ddlBankName.SelectedValue);
            }
        }

        private void fillFileFormat(String fileType,String bankId)
        {
            UploadHelper objUploadHelper = null;
            List<FileFormat> bankLst = null;
            try
            {
                objUploadHelper = new UploadHelper();
                bankLst = objUploadHelper.getFileTypeByCustomer(((User)Session["CurrentUserVO"]).CustomerID, fileType, bankId);
                if (bankLst != null && bankLst.Count > 0)
                {
                    //field_mapping_id,file_format,separator
                    for (int i = 0; i < bankLst.Count; i++)
                    {
                        rbFileType.Items.Add(bankLst[i].FileFormats.Trim());
                        rbFileType.Items[i].Value = (bankLst[i].FieldMappingId.Trim());
                    }
                    rbFileType.SelectedIndex = 0;
                }
                else
                { 
                }
            }
            catch (Exception ex)
            {
                if(ex!=null)
                {
                    throw;
                }
            }
            finally
            {
                if (objUploadHelper != null)
                {
                    objUploadHelper = null;
                }
                if (bankLst != null)
                {
                    bankLst = null;
                }
            }
        }
    }
}